package br.brpv.silvestrin.vendas.mainactivity;

import java.util.ArrayList;

import android.app.ActionBar;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import br.brpv.silvestrin.vendas.R;
import br.brpv.silvestrin.vendas.domain.AddedItem;
import br.brpv.silvestrin.vendas.domain.AddedItemAdapter;
import br.brpv.silvestrin.vendas.domain.Order;
import br.brpv.silvestrin.vendas.domain.OrderAdapter;
import br.brpv.silvestrin.vendas.manager.OrderManager;
import br.brpv.silvestrin.vendas.util.ShowMessage;
import br.brpv.silvestrin.vendas.webservice.ServerConnection;
import br.brpv.silvestrin.vendas.webservice.ServerDataCacheService;

public class SavedOrdersFragment extends CompanyFragment implements OrderManager.OrderManagerInterface
{
    private static final String SAVE_ORDERS_LIST = "saveOrdersList";
    private static final String SAVE_COD_COMPANY = "saveCodCompany";
    
    public static final String ADD_ITEM_LIST_FRAGMENT = "AddItemListFragment";
    
    private OrderAdapter orderAdapter = null;
    private AddedItemAdapter addedItemAdapter = null;
    private ListView ordersListView = null;
    private ListView addedItemListView = null;
    private Button finalizeButton = null;
    private Button editButton = null;
    private Button removeButton = null;

    private Order selectedOrder = null;

    private ServerDataCacheService mServerDataCacheBinder;
    private boolean mBound;
    private OrderManager orderManager;
    private OnEditOrderListener mEditOrderListener;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //bind on ServerDataCacheService
        Intent intent = new Intent(getActivity(), ServerDataCacheService.class);
        getActivity().bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        
        addedItemAdapter = new AddedItemAdapter(getActivity(), R.layout.list_view_rows_added_item, new ArrayList<AddedItem>());

        orderManager = new OrderManager(getActivity(), this);

        /*if(savedInstanceState != null) {
            loadSavedOrdersList(savedInstanceState);
        } else {
        	getSavedOrdersList();
        }*/
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.saved_orders_layout, container, false);
        
        return v;
    }
    
    @Override
	public void onActivityCreated(Bundle savedInstanceState) {
    	ordersListView = (ListView) getActivity().findViewById(R.id.saved_order_list);
    	if(ordersListView != null) {
        	ordersListView.setAdapter(orderAdapter);
        	ordersListView.setOnItemClickListener(new OrdersListClickListener(this));
        	ordersListView.setDrawSelectorOnTop(true);
    	}
    	
    	addedItemListView = (ListView) getActivity().findViewById(R.id.addedItems_list);
    	if(addedItemListView != null) {
    		addedItemListView.setAdapter(addedItemAdapter);
    		addedItemListView.setOnItemClickListener(null);
    		addedItemListView.setDrawSelectorOnTop(true);
    	}
    	
    	finalizeButton = (Button) getActivity().findViewById(R.id.saved_orders_finalize);
    	if(finalizeButton != null) {
    		finalizeButton.setOnClickListener(new FinalizeSavedOrderListener(this));
    		if(selectedOrder == null) finalizeButton.setEnabled(false);
    	}

        editButton = (Button)getActivity().findViewById(R.id.saved_orders_edit);
        if(editButton != null) {
            editButton.setOnClickListener(new EditSavedOrderListener());
            if(selectedOrder == null) editButton.setEnabled(false);
        }

        removeButton = (Button)getActivity().findViewById(R.id.saved_orders_remove);
        if(removeButton != null) {
            removeButton.setOnClickListener(new RemoveOrderListener());
            if(selectedOrder == null) removeButton.setEnabled(false);
        }

        getSavedOrdersList();

		super.onActivityCreated(savedInstanceState);
	}



    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        try {
            mEditOrderListener = (OnEditOrderListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnEditOrderListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        if (mBound) {
            getActivity().unbindService(mConnection);
            mBound = false;
        }
    }
	
	private ServiceConnection mConnection = new ServiceConnection(){

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            ServerDataCacheService.LocalBinder localBinder = (ServerDataCacheService.LocalBinder)iBinder;

            mServerDataCacheBinder = localBinder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBound = false;
        }
    };

    public void loadSavedOrdersList(Bundle savedInstanceState){
        if(savedInstanceState != null) {
            ArrayList<Parcelable> savedArray = savedInstanceState.getParcelableArrayList(SAVE_ORDERS_LIST);
            ArrayList<Order> ordersArray = new ArrayList<Order>();

            for(Parcelable p: savedArray) {
                ordersArray.add((Order) p);
            }

            codSelectedCompany = savedInstanceState.getInt(SAVE_COD_COMPANY);

            updateSavedOrdersList(ordersArray);
        }
    }
    
    private void getSavedOrdersList() {
        /*ArrayList<Order> ordersList = null;
        // TODO permitir atualizar a lista, sem ter que mudar de empresa ou sair da MainActivity e voltar
        if(mServerDataCacheBinder != null) ordersList = mServerDataCacheBinder.getSavedOrderList(codSelectedCompany);
        if(ordersList == null || ordersList.size() == 0) { 
        	ServerConnection.getSavedOrders(0, Integer.valueOf(user.getId()), codSelectedCompany, this);
        }
        else updateSavedOrdersList(ordersList);*/
    	ServerConnection.getSavedOrders(0, Integer.valueOf(user.getId()), codSelectedCompany, this);
    	if(finalizeButton != null) finalizeButton.setEnabled(false);
        if(editButton != null) editButton.setEnabled(false);
        if(removeButton != null) removeButton.setEnabled(false);

    }
    
    private void updateSavedOrdersList(ArrayList<Order> orders) {
        if(mServerDataCacheBinder != null) mServerDataCacheBinder.addSavedOrderListToCompany(codSelectedCompany, orders);
        orderAdapter = new OrderAdapter(getActivity(), orders);
        
        if(ordersListView != null) {
        	ordersListView.setAdapter(orderAdapter);
        	orderAdapter.notifyDataSetChanged();
        }
        
        addedItemAdapter.clear();
        addedItemAdapter.notifyDataSetChanged();
    }

    /*********LISTENERS***********/
    private class OrdersListClickListener implements AdapterView.OnItemClickListener {
    	private SavedOrdersFragment savedOrdersFragment;
    	
		public OrdersListClickListener(SavedOrdersFragment savedOrdersFragment) {
			this.savedOrdersFragment = savedOrdersFragment;
		}

		@Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
			int orderId = Integer.valueOf(orderAdapter.getItem(i).getId());
			ServerConnection.getItemsFromSavedOrder(orderId, 0, savedOrdersFragment);
			
			selectedOrder = orderAdapter.getItem(i);
			finalizeButton.setEnabled(true);
            editButton.setEnabled(true);
            if(removeButton != null) removeButton.setEnabled(true);
		}
    	
    }
    
    private class FinalizeSavedOrderListener implements View.OnClickListener {
    	private SavedOrdersFragment savedOrdersFragment;
    	
    	public FinalizeSavedOrderListener(SavedOrdersFragment savedOrdersFragment) {
    		this.savedOrdersFragment = savedOrdersFragment;
    	}
    	
		@Override
		public void onClick(View v) {
            //TODO finalizar o pedido
			//ServerConnection.finalizeOrder(selectedOrder.getId(), Order.STATUS_FINALIZE, )
            orderManager.finalizeOrder(selectedOrder.getId());
        }
    }


    private class EditSavedOrderListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            mEditOrderListener.onEditOrderClick(selectedOrder, addedItemAdapter.getObjects());
        }
    }

    private class RemoveOrderListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            orderManager.removeOrder(selectedOrder.getId());
            mEditOrderListener.onRemoveOrderClick(selectedOrder.getId());
        }
    }


    public interface OnEditOrderListener {
        public void onEditOrderClick(Order order, ArrayList<AddedItem> items);
        public void onRemoveOrderClick(String orderId);
    }
    /****************************/
    
    /*****Getters and Setters*****/
    public void setSelectedCompany(int cod) {
        //se o fragmento nao foi inicializado nao chama o servidor pois sera chamado no OnCreate
        if(this.codSelectedCompany == -1) {
        	this.codSelectedCompany = cod;
        	return;
        }
        
        if(this.codSelectedCompany != cod){
            this.codSelectedCompany = cod;
            getSavedOrdersList();
        }
    }

    @Override
    public int getSelectedCompany() {
        return codSelectedCompany;
    }
    /*****************************/

    /*****WEB SERVICE CALLBACKS***/
	public void OnWebServiceSavedOrdersReturn(ArrayList<Order> ordersList) {
		updateSavedOrdersList(ordersList);
	}

	public void failedOnRetrieveSavedOrders() {
		final SavedOrdersFragment fragment = this;
		
		ShowMessage.alertDialog2(getActivity(), R.string.saved_orders_failedonretrievesavedorders,
				new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch(which) {
				case DialogInterface.BUTTON_NEGATIVE:
					getActivity().finish();
					break;
				case DialogInterface.BUTTON_POSITIVE:
					ServerConnection.getSavedOrders(0, Integer.valueOf(user.getId()), codSelectedCompany, fragment);
					break;
				}
			}
		});
	}

	public void OnWebServiceItemsFromSavedOrderReturn( ArrayList<AddedItem> itemsList) {
		addedItemAdapter.clear();
		addedItemAdapter.addAll(itemsList);
		addedItemAdapter.notifyDataSetChanged();
	}

	public void failedOnRetrieveItemsFromSavedOrder() {
		//TODO avisar erro
	}
	


	public void failedOnFinalizeSavedOrder() {
		//TODO avisar erro
	}
    /****************************/

	@Override
	public void refresh() {
		getSavedOrdersList();
	}


    @Override
    public void orderInitialized(Order order) {
    }

    @Override
    public void orderFinalized(Order order) {
    }

    @Override
    public void orderFromSaveToFinalized(String orderId) {
        refresh();
    }

    @Override
    public void onValorBrutoReturn(String valorBruto) {
    }

    @Override
    public void onValorLiquidoReturn(String valorLiquido) {
    }

    @Override
    public void onItemsAdded(ArrayList<AddedItem> itemsSent) {
    }

    @Override
    public void onItemRemoved(String itemId) {
    }

    @Override
    public void onItemAdded(AddedItem item) {
    }

    @Override
    public void orderRemoved(String resultString) {
        refresh();
    }


}
